import {validateNull} from "@/util/validate"
import _omit from 'lodash/omit'

export default {
    data() {
        return {}
    },
    methods: {
        /**
         * 设置父节点选择操作
         * @param ref       组件引用
         * @param node      树节点
         * @param options   选项
         */
        setParentCheckedHandler(ref, node, options = {checked: true, deep: false}) {
            // 是否为一级节点
            if (node.level === 1) {
                return
            }
            // 获取父节点
            const parentNode = node.parent
            if (parentNode) {
                // 设置勾选状态
                ref.setChecked(parentNode.key, options.checked, false)
            }
            if (options.deep) {
                this.setParentCheckedHandler(ref, parentNode, options)
            }
        },
        /**
         * 设置子节点选中操作
         * @param ref       组件引用
         * @param node      树节点
         * @param options   选项
         */
        setChildrenCheckedHandler(ref, node, options = {checked: true, deep: false}) {
            // 获取子节点
            const childNodes = node.childNodes
            if (validateNull(childNodes)) {
                return
            }
            childNodes.forEach((childNode, index, array) => {
                // 设置勾选状态
                ref.setChecked(childNode.key, options.checked, false)
                if (options.deep) {
                    this.setChildrenCheckedHandler(ref, childNode, options)
                }
            })
        },
      /**
       * 设置子节点是否禁用操作
       * @param ref       组件引用
       * @param node      树节点
       * @param options   选项
       */
      setChildrenDisabledHandler(ref, node, options = {disabled: true, deep: false}) {
        // 获取子节点
        const childNodes = node.childNodes
        if (validateNull(childNodes)) {
          return
        }
        childNodes.forEach((childNode, index, array) => {
          // 设置禁用状态
          childNode.data['disabled'] = options.disabled
          if (options.deep) {
            this.setChildrenDisabledHandler(ref, childNode, options)
          }
        })
      },
        /**
         * 将树形数据转换为数组，并且去除子节点属性
         * @param source
         * @param options
         * @returns {[]}
         */
        treeConvertArrayHandler(source = [], options = {children: 'children'}) {
            let target = []
            source.forEach((element, index, array) => {
                target.push(_omit(element, [options.children]))
                if (!validateNull(element[options.children])) {
                    target = target.concat(this.treeConvertArrayHandler(element[options.children]))
                }
            })
            return target
        }
    }
}
